package models

import (
	"3rd/errors"
	"bytes"
	"encoding/json"
	"github.com/astaxie/beego/validation"
	"io/ioutil"
	"net/http"
	"strconv"
		goerrors "github.com/go-errors/errors"
)

type QS struct {
	Qid string `json:"qid" valid:"Required"`
	Sid string `json:"sid" valid:"Required"`
}

var uc string

func (this *QS) Validate() error {
	// request body
	in, err := json.Marshal(this)
	if err != nil {
		return goerrors.New(err)
	}
	buffer := new(bytes.Buffer)
	buffer.Write(in)
	// request
	resp, err := http.Post(uc+"/uc/validate", "json", buffer)
	if err != nil {
		return goerrors.New(err)
	}
	out, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return goerrors.New(err)
	}
	// parse response
	var rst errors.CustomError
	if err := json.Unmarshal(out, &rst); err != nil {
		return errors.New(UcFailed, err)
	}
	if !rst.IsSuccess() {
		return errors.New(ValidateError, "invalid qid or sid:"+rst.Msg)
	}

	return nil
}

func (this *QS) Valid(v *validation.Validation) {
	if err := this.Validate(); err != nil {
		v.SetError(strconv.Itoa(ValidateError), err.Error())
	}
}

//type StationAdmin struct {
//	QS `,inline valid:"Required"`
//	StationID string `json:"stationID" valid:"Required"`
//}

//func (this *StationAdmin) Validate() error {
//	if err := this.QS.Validate(); err != nil {
//		return err
//	}

//	return nil
//}

//func (this *StationAdmin) Valid(v *validation.Validation) {
//	if err := this.Validate(); err != nil {
//		// TODO:
//		v.SetError("invalid stationID", "invalid stationID")
//	}
//}

/*
func Register() error {
	registerUrl := uc + "/uc/registerSilently"
	buffer := new(bytes.Buffer)
	type User struct {
	Qid       string `json:"qid"`
	AvatarUrl string `json:"avatarUrl" `
	UserName  string `json:"name" valid:"Required"`
	Email     string `json:"email"`
	Mobile    string `json:"mobile"`
	Company   string `json:"company"`
	RealName  string `json:"realName"`
	TelePhone string `json:"telePhone"`
	Password  string `json:"password" valid:"Required"`
	mediaType string
	Created   int64 `json:"created"`
}
	status, _, rc, err := http.DefaultClient.Post(registerUrl, nil, buffer)
	if err != nil {
		return err
	}
		if !status.IsSuccess() {
		return errors.New("")
	}

	defer rc.Close()

	type Resp struct {
		UserName string `json:"userName"`
		Qid      string `json:"qid"`
		Sid      string `json:"sid"`
	}
	var resp Resp
	if err := json.Unmarshal(rc, &resp); err != nil {
		return err
	}

	return nil
}*/
